package com.lepu.app.fun.chat.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.chat.adapter.ChatMessageAdapter;
import com.lepu.app.fun.chat.bean.BeanDoctorOnline;
import com.lepu.app.fun.chat.bean.BeanStaffEntity;
import com.lepu.app.fun.chat.bean.ChatMessage;
import com.lepu.app.fun.chat.bean.ChatRoomMessage;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.bean.Media;
import com.lepu.app.fun.chat.core.ChatManager;
import com.lepu.app.fun.chat.core.MessageBuilder;
import com.lepu.app.fun.chat.util.ChatConst;
import com.lepu.app.fun.chat.util.Constants;
import com.lepu.app.fun.chat.util.ChatSendListener;
import com.lepu.app.fun.chat.util.VoicePlayClickListener;
import com.lepu.app.fun.my.MyConsultActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

/**
 * 在线咨询 只允许发送纯文本
 *
 * @author wxd
 */
public class ChatFragmentOnline extends ChatFragmentBase implements
        OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
        AsyncRequest, ChatSendListener, Observer, SwipeRefreshLayout.OnRefreshListener {

    private static final int MSG_INIT_DATA = 10;
    private static final int MSG_LOAD_MORE_DATA = 11;

    private static final String REQUEST_ONLINE_CONSULT = "request_online_consult";

    private boolean mInitDataSuccess = false;// 是否加载完数据
    private BaseFragmentActivity mBaseFragmentActivity = null;

    public BeanDoctorOnline mBeanDoctorOnline = null;
    private CustomTopBarNew mTopbar = null;

    private ChatMessageAdapter mDataAdapter = null;
    private LinkedList<ChatMessage> mDataList = new LinkedList<ChatMessage>();
    private ChatSession mChatSession = new ChatSession();

    private long mSendTime = 0l;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mNeedSendFile = true;
        mNeedSendSound = false;
        mView = LayoutInflater.from(getActivity()).inflate(
                R.layout.chat_fragment_online, null, false);
        super.onCreateView(inflater, container, savedInstanceState);
        init();
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();

        UmengHelper.onResume(getActivity(),
                UmengEvent.page_lianxikefu);
    }

    @Override
    public void onPause() {
        super.onPause();

        UmengHelper.onPause(getActivity(),
                UmengEvent.page_lianxikefu);
        LoginUtil.clearStaffMsgNewCount();
        //ChatManager.getInstance().resetNewMsgCount(mChatSession.getSessionId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mInitDataSuccess = false;
        ObserverManager.getInstance().removeObserver(this);
        stopVoice();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (!mInitDataSuccess) {
                // 第一次进入页面获取数据
                mInitDataSuccess = true;
            }
        }
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        mBaseFragmentActivity.finish(true);
    }

    @Override
    public void onTopbarRightButtonSelected() {
        Intent intent = new Intent(mBaseFragmentActivity,
                MyConsultActivity.class);
        mBaseFragmentActivity.startActivity(intent, true);
    }

    /*
     * 初始化ui控件，不要初始化数据！！！！
     *
     * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
     */
    private void init() {
        mTopbar = (CustomTopBarNew) mView.findViewById(R.id.topbar);
        mTopbar.setTopbarTitle("问问题");
        mTopbar.setonTopbarNewLeftLayoutListener(this);
//		mTopbar.setRightText("常见问题");
//		mTopbar.setOnTopbarNewRightButtonListener(this);

        mBaseFragmentActivity = (BaseFragmentActivity) getActivity();
        mChatSendListener = this;
        mRefreshLayout.setOnRefreshListener(this);

        requestConsult();

        // add listen
        ObserverManager.getInstance().addObserver(
                ObserverConst.NOTIFY_CHAT_MESSAGE_ONLINE, this);

        new Thread(new Runnable() {

            @Override
            public void run() {
                initData();
            }
        }).start();
    }

    private void stopVoice() {
        VoicePlayClickListener voicePlayClickListener = VoicePlayClickListener.currentPlayListener;
        if (voicePlayClickListener != null) {
            voicePlayClickListener.stopVoice();
        }
    }

    private void initData() {
        // 默认发送过来的数据，提示用户
        String defaultData = getResources().getString(
                R.string.index_online_chat_default_tip);
        //defaultData = BeanStaffEntity.getDefaultReceiveData(defaultData);

        ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(
                mChatSession, defaultData);
        chatMessage.setDirection(Constants.Chat.CHAT_DIRECTION_RECEIVE);// 发送来
        mDataList.add(chatMessage);

        List<ChatMessage> dataList = ChatManager.getInstance().getChatMessagesStaff(
                Constants.Staff, false, 0);
        if (dataList == null || dataList.size() == 0) {

        } else {
            for (int i = 0; i < dataList.size(); i++) {
                dataList.get(i).setGuestProfilePicId(
                        mChatSession.getUserProfilePictureId());
            }
            addLastList(dataList);
        }
        mHandler.sendEmptyMessage(MSG_INIT_DATA);
    }

    private void addFirstList(List<ChatMessage> dataList) {
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                ChatMessage message = dataList.get(i);
                mDataList.addFirst(message);
                mDataAdapter.addImageData(message, false);
            }
        }
    }

    private void addLastList(List<ChatMessage> dataList) {
        if (dataList != null && dataList.size() > 0) {
            for (int i = dataList.size() - 1; i >= 0; i--) {
                ChatMessage message = dataList.get(i);
                mDataList.add(message);
            }
        }
    }

    /**
     * 检查聊天发送数据操作是否太快
     *
     * @return
     */
    private boolean checkChatQucik() {
        boolean flag = false;
        if (mSendTime == 0) {
            flag = true;
        } else {
            long value = System.currentTimeMillis() - mSendTime;
            if (value < 1000) {
                LogUtilBase.LogD(null, "操作太快");
                flag = false;
            } else {
                flag = true;
            }
        }
        mSendTime = System.currentTimeMillis();
        return flag;
    }

    private void showOperationQuickDialog() {
        MyDialog dialog = new MyDialog(getActivity())
                .setMessage("请不要操作太快！")
                .setNegativeButtonSplitImageHide(true)
                .setPositiveButton(R.string.app_ok,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        });

        dialog.create(null);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.showMyDialog();
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_INIT_DATA:

                    mDataAdapter = new ChatMessageAdapter(getActivity(), ChatFragmentOnline.this, mDataList,
                            ChatConst.TYPE_ONLINE_CHAT_ONLINE,mDataListview);
                    mDataListview.setAdapter(mDataAdapter);

                    scrollBottom();
                    break;
                case MSG_LOAD_MORE_DATA:

                    mRefreshLayout.setRefreshing(false);

                    List<ChatMessage> dataList = (List<ChatMessage>) msg.obj;
                    if (dataList != null && dataList.size() > 0) {
                        addFirstList(dataList);
                        mDataAdapter.notifyDataSetChanged();
                        mDataListview.setSelection(dataList.size() - 1);
                        mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
                    } else {

                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    public void requestConsult() {

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();

        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

            params.put("Category", 3);
        } catch (Exception e) {
        }
        map.put("ht", params);

        mBaseFragmentActivity.showProgressDialog();
        ApiClient.http_post_main(Setting.getContactDoctorUrl(), map, null,
                this, REQUEST_ONLINE_CONSULT, true);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_ONLINE_CONSULT)) {
            mBaseFragmentActivity.hideProgressDialog();

            mBeanDoctorOnline = BeanDoctorOnline.parseDetailInfo((String) data);
            if (mBeanDoctorOnline != null
                    && !TextUtils.isEmpty(mBeanDoctorOnline.DoctorID)) {
                //mTopbar.setTopbarTitle(mBeanDoctorOnline.DoctorName);
                mChatSession.setUserId(UtilityBase
                        .parseLong(mBeanDoctorOnline.DoctorID));

                String content = mChatContentEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    sendText(content);
                }
            }
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String data) {
        if (object.equals(REQUEST_ONLINE_CONSULT)) {
            mBaseFragmentActivity.hideProgressDialog();
        }
    }

//	private void initChatSession()
//	{
//		BeanChatTo beanChatTo = new BeanChatTo();
//		beanChatTo.UserID = mBeanDoctorOnline.DoctorID;
//		beanChatTo.NickName = mBeanDoctorOnline.DoctorName;
//		beanChatTo.Gender = "";
//		beanChatTo.Avatar = "";
//		
//		mChatSession = ChatManager.getInstance()
//				.getOrCreateChatSessionStaff(
//						Long.valueOf(LoginUtil.getUserId()),
//						beanChatTo,Constants.Staff);
//	}

    // ===============================================================================
    @Override
    public void sendText(String content) {

        if (mBeanDoctorOnline == null
                || TextUtils.isEmpty(mBeanDoctorOnline.DoctorID)) {
            requestConsult();
            return;
        }

        if (!checkChatQucik()) {
            showOperationQuickDialog();
            return;
        }

        if (!TextUtils.isEmpty(content)) {

            //mChatSession.setSessionId(Constants.Staff);

            ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(
                    mChatSession, content);
            ChatManager.getInstance().sendMessageToStaff(mChatSession,
                    chatMessage);

            mChatContentEditText.setText("");
            mDataListview.setSelection(mDataList.size() - 1);
        } else {
            // base fragment sendText
            // 实际上已经做了非空的处理，统一做了提示
        }
    }

    @Override
    public boolean sendPhoto(String imageFilePath) {
        boolean flag = false;
        File file = null;
        if (TextUtils.isEmpty(imageFilePath)) {
            flag = true;
        } else {
            file = new File(imageFilePath);
            if (!file.exists()) {
                flag = true;
            }
        }

        if (flag) {
            UIHelper.showToast(getActivity(), "获取媒体资源失败");
        } else {
            ChatMessage chatMessage = MessageBuilder.buildNewImageMessage(
                    mChatSession, imageFilePath,
                    Constants.Chat.CHAT_IMAGE_STYLE_LARGE, (int) file.length(),
                    false);
            chatMessage.setFromUserId(Constants.Staff); // 固定一个人
            ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                    chatMessage);
        }
        return flag;
    }

    @Override
    public void sendPhotos(ArrayList<String> photoFileList) {
        if (photoFileList != null && photoFileList.size() > 0) {
            for (int i = 0; i < photoFileList.size(); i++) {
                String filePath = photoFileList.get(i);
                sendPhoto(filePath);
            }
        }
    }

    @Override
    public boolean sendVoice(String voiceFilePath) {
        File file = new File(voiceFilePath);
        int duration = 0;
        long size = file.length();

        MediaPlayer mp = MediaPlayer.create(getActivity(),
                Uri.parse(voiceFilePath));
        duration = mp.getDuration();// ms

        ChatMessage chatMessage = MessageBuilder.buildNewAudioMessage(
                mChatSession, voiceFilePath, duration, size,
                Constants.Chat.CHAT_MIME_TYPE_AMR, false);
        chatMessage.setFromUserId(Constants.Staff); // 固定一个人
        ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                chatMessage);

        return true;
    }

    //===========================

    /**
     * 重新发送
     *
     * @param position
     */
    @Override
    public void reSendContent(int position) {

        if (!checkChatQucik()) {
            showOperationQuickDialog();
            return;
        }

        ChatMessage message = mDataList.get(position);
        mDataList.remove(position);
        mDataAdapter.removeImageData(message);

        if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_TEXT) {
            String sendStr = message.getContent();
            //mChatSession.setSessionId(Constants.Staff);

            ChatMessage chatMessage = MessageBuilder.buildResendTextMessage(
                    mChatSession, sendStr, message.getMessageId());
            ChatManager.getInstance().sendMessageToStaff(mChatSession,
                    chatMessage);

            mChatContentEditText.setText("");
            mDataListview.setSelection(mDataList.size() - 1);
        } else if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_IMAGE) {
            Media media = message.getMedia();
            if (media == null) {
                return;
            }

            String imageFilePath = message.getMedia().getFullName();

            File file = new File(imageFilePath);
            if (file.exists()) {
                ChatMessage chatMessage = MessageBuilder.buildResendImageMessage(
                        message.getMessageId(), mChatSession, imageFilePath,
                        Constants.Chat.CHAT_IMAGE_STYLE_LARGE, (int) file.length(),
                        true);
                chatMessage.setFromUserId(Constants.Staff); // 固定一个人
                ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                        chatMessage);
            }
        } else if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_AUDIO) {
            // 暂时不支持语音

            Media media = message.getMedia();
            if (media == null) {
                return;
            }
            ChatMessage chatMessage = MessageBuilder.buildResendAudioMessage(
                    message.getMessageId(), mChatSession, media.getFullName(),
                    media.getDuration(), media.getObjectSize(),
                    Constants.Chat.CHAT_MIME_TYPE_AMR);
            chatMessage.setFromUserId(Constants.Staff); // 固定一个人
            ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                    chatMessage);
        }
    }

    /**
     * main thread
     */
    @Override
    public void notify(String name, Object sender, Object data) {

        if (name.equals(ObserverConst.NOTIFY_CHAT_MESSAGE_ONLINE)) {

            int msgWhat = (Integer) sender;

            ChatMessage message = (ChatMessage) data;

            if (null == message) {
                return;
            }

            long sessionId = mChatSession.getSessionId();
            if (sessionId != message.getSessionId()) {
                return;
            }

            boolean isNew = false;
            switch (msgWhat) {
                case Constants.Chat.CHAT_MESSAGE_SENT:
                    LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_SENT");

                    mDataList.add(message);

                    mDataAdapter.addImageData(message, true);
                    mDataAdapter.notifyDataSetChanged();
                    scrollBottom();
                    break;
                case Constants.Chat.CHAT_MESSAGE_RECEIVED:
                    LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_RECEIVED");
//				isNew = true;
//				for (int i = 0; i < mDataList.size(); i++) {
//					if (mDataList.get(i).getMessageId()
//							.equals(message.getMessageId())) {
//						//mDataList.set(i, message);
//						isNew = false;
//						break;
//					}
//				}
//
//				if (isNew) {
//					mDataList.add(message);
//				}

                    mDataList.add(message);
                    mDataAdapter.addImageData(message, true);
                    mDataAdapter.notifyDataSetChanged();
                    scrollBottom();
                    break;
                case Constants.Chat.CHAT_MESSAGE_CHANGED:
                    LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_CHANGED");
                    for (int i = mDataList.size() - 1; i >= 0; i--) {
                        if (mDataList.get(i).getMessageId()
                                .equals(message.getMessageId())) {
                            mDataList.set(i, message);
                            break;
                        }
                    }
                    mDataAdapter.notifyDataSetChanged();
                    //scrollBottom();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onRefresh() {
        new Thread(new Runnable() {

            @Override
            public void run() {

                int fromCount = mDataList.size();
                List<ChatMessage> dataList = ChatManager.getInstance().getChatMessagesStaff(
                        Constants.Staff, false, fromCount);

                Message msg = mHandler.obtainMessage();
                msg.obj = dataList;
                msg.what = MSG_LOAD_MORE_DATA;
                mHandler.sendMessageDelayed(msg, 100);
            }
        }).start();
    }
}
